<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\SmsServices;
use Illuminate\Http\Request;

class UserController extends Controller
{
    protected $request;
    protected $redis;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->redis = new \Predis\Client('127.0.0.1:6379');
//        dd($this->redis);
    }

    public function sendSms()
    {
        $stdData = array();
        $mobile = $this->request->post('mobile', 0);
        if(!$mobile) return json_encode(['code' => -1, 'msg' => '手机号码不能为空', 'data' => []]);

        $redisKey = $mobile . '_capatch';
        $capatch = $this->redis->get($redisKey);
        if($capatch)
        {
            $stdData = array(
                'capatch' => $capatch
            );

            return json_encode(['code' => 200, 'msg' => 'success', 'data' => $stdData]);
        }
        $smsService = new SmsServices();
        $smsResult = $smsService->sendSms($mobile);
        if($smsResult['code'] == '短信发送成功')
        {
            $this->redis->setex($redisKey, 1300, $smsResult['capatch']);
        }
        $stdData = array(
            'capatch' => $smsResult['capatch']
        );

        return json_encode(['code' => 200, 'msg' => 'success', 'data' => $stdData]);
    }

    public function login()
    {
        $mobile = $this->request->post('mobile', 0);
        $capatch = $this->request->post('capatch', 0);
        if(!$mobile || !$capatch) return json_encode(['code' => -1, 'msg' => '参数错误', 'data' => []]);

        $redisKey = $mobile . '_capatch';
        $verifyCapatch = $this->redis->get($redisKey);
        if(!$verifyCapatch) return json_encode(['code' => -1, 'msg' => '验证码已过期', 'data' => []]);

        if($capatch != $verifyCapatch) return json_encode(['code' => -1, 'msg' => '验证码不匹配', 'data' => []]);

        $user = new User();

        $userInfo = $user->getUserInfo($mobile);

        // 登录
        if($userInfo)
        {
            return json_encode(['code' => 200, 'msg' => 'success', 'data' => $userInfo]);
        }
        // 注册
        else
        {
            $createData = array(
                'phone' => $mobile,
            );
            $userRes = $user->create($createData);
            if($userRes)
            {
                return json_encode(['code' => 200, 'msg' => 'success', 'data' => $userRes]);
            }
            else
            {
                return json_encode(['code' => -1, 'msg' => '注册失败', 'data' => []]);
            }
        }
    }



    public function lists()
    {
        echo phpinfo();
    }
     public function lists()
    {
        echo phpinfo();
    }
}
